/**    
 * 文件名： PatientRegistries.java    
 *    
 * 版本信息：    
 * 日期：2010-11-10    
 * Copyright Corporation 2010     
 * 版权所有       
 */

package com.sunwayhorizo.health.business.patad.empi;

import com.sunwayhorizo.health.common.*;
import com.sunwayhorizo.health.ets.factory.DictionaryFactory;
import com.sunwayhorizo.health.hl7.common.*;

import java.util.*;
import javax.ejb.*;
import org.jboss.seam.*;
import org.jboss.seam.annotations.*;
import com.sunwayhorizo.health.business.base.*;
import com.sunwayhorizo.health.business.dto.*;
import com.sunwayhorizo.health.business.dto.patad.empi.*;
import com.sunwayhorizo.health.business.dto.patad.encounter.*;
import com.sunwayhorizo.health.business.dto.registries.*;
import com.sunwayhorizo.health.business.patad.empi.query.*;
import com.sunwayhorizo.health.business.patad.encounter.*;
import com.sunwayhorizo.health.business.patad.encounter.query.*;
import com.sunwayhorizo.health.business.registries.organization.*;
import com.sunwayhorizo.health.business.registries.organization.query.*;
import com.sunwayhorizo.health.business.registries.person.*;
import com.sunwayhorizo.health.hl7.datatypes.*;
import com.sunwayhorizo.health.hl7.persistent.*;
import com.sunwayhorizo.health.hl7.rim.*;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.rim.Rolelink;
import com.sunwayhorizo.health.hl7.vocabulary.*;

/**
 * @Title: PatientRegistries.java
 * @Package com.sunwayhorizo.health.business.registries
 * @Description: 患者登记
 * @version V1.0
 * @firstAuthor obama
 * @firstTime 2010-03-15 13:42:59
 * @lastAuthor obama
 * @lastTime 2011-04-14 15:42:59
 */

@Name("PatientManager")
@Stateless
public class PatientManager extends BaseManager implements PatientManagerLocal
{
    private PatientManagerLocal patientManager = (PatientManagerLocal) Component.getInstance("PatientManager");
    private PatientQueryLocal patientQuery = (PatientQueryLocal) Component.getInstance("PatientQuery");
    private PatientEncounterQueryLocal patientEncounterQuery = (PatientEncounterQueryLocal) Component.getInstance("PatientEncounterQuery");
    private PersonManagerLocal personManager = (PersonManagerLocal) Component.getInstance("PersonManager");
    private OrganizationManagerLocal organizationManager = (OrganizationManagerLocal) Component.getInstance("OrganizationManager");
    private OrganizationQueryLocal organizationQuery = (OrganizationQueryLocal) Component.getInstance("OrganizationQuery");


    // 新建主索引
    @Override
    public ResultsDTO newPatientIndex(EntitysDTO entityDTO) throws Hl7Exception
    {

        ResultsDTO resultsDTO = validateNewIndex(entityDTO);
        if (resultsDTO != null)
        {
            return resultsDTO;
        }

        // 构建注册动作
        Act registrationAct = this.getActFactory().newRegistryAct(ActMood.EVN, null, null);

        // 构建人的实体
        Person person = constructPerson(entityDTO);

        // 构建患者角色并参与动作中
        Patient patient = constructPatient(entityDTO, person);
        ActParticipation patPart = getActFactory().newActParticipation();
        patPart.setTypeCode(ParticipationType.SBJ);
        addParticipation(patient, patPart);

        // 构建自然角色(社会角色)
        Role natureRole = constructNatureRole(entityDTO, person);

        // 增加自然角色和患者角色关联
        Rolelink patRolelink = new Rolelink();
        patRolelink.setTypeCode(RoleLinkType.CONT);
        addRoleLink(natureRole, patient, patRolelink);

        // 并参与注册动作中
        ActParticipation natPart = getActFactory().newActParticipation();
        natPart.setTypeCode(ParticipationType.SBJ);
        addParticipation(natureRole, natPart);

        // 构建家庭角色
        List<Role> familyRoles = constructFamilyRole(entityDTO, person);
        // 增加自然角色和家庭角色关联、家庭角色参与注册动作
        for (int i = 0; i < familyRoles.size(); i++)
        {
            Rolelink rl = new Rolelink();
            rl.setTypeCode(RoleLinkType.CONT);
            rl.setSequenceNumber(DataTypeUtil.getINT((long) (i + 1)));
            rl.setDescribe(DataTypeUtil.getCS(entityDTO.getListHome().get(i).getTypeDic().getConceptName()));
            addRoleLink(natureRole, familyRoles.get(i), rl);

            ActParticipation famiPat = getActFactory().newActParticipation();
            famiPat.setTypeCode(ParticipationType.SBJ);
            addParticipation(natureRole, famiPat);
        }

        ControlAct controlAct = newControlAct(registrationAct);
        // 提交此次事务
        save(controlAct);
        log.info("PatientManager-newPatientIndex-新建患者成功！");
        return getResultsDTO("患者信息保存成功", true, patient.getRoleId().toString());
    }


    public ResultsDTO modifyPatient(EntitysDTO patientDTO) throws Hl7Exception
    {
        // 判断患者ID是否为空
        if (!StrUtil.isEmpty(patientDTO.getPatientBaseInfo().getNatureId()))
        {
            // 查找患者
            Patient patient = patientQuery.findPatientByNeturalId(patientDTO.getPatientBaseInfo().getNatureId());
            if (patient != null)
            {
                // 修改人的信息
                personManager.modifyPerson((Person) patient.getPlayerEntity(), patientDTO);
                // 修改患者的医保信息

                update(patient);

                Role natureRole = getNatureRoleByPatient(patient);
                if (natureRole != null)
                {
                    updateNatureRole(natureRole, patientDTO);
                }
                else
                {
                    natureRole = constructNatureRole(patientDTO, (Person) patient.getPlayerEntity());
                    Rolelink link = new Rolelink();
                    link.setTypeCode(RoleLinkType.CONT);
                    link.setSourceRole(natureRole);
                    link.setTargetRole(patient);

                    ControlAct ca = (ControlAct) patient.getControlAct();

                    link.setControlAct(ca);
                    natureRole.getScoperEntity().setControlAct(ca);
                    natureRole.setControlAct(ca);

                    em.persist(natureRole.getScoperEntity());
                    em.persist(natureRole);
                    em.persist(link);

                    em.flush();
                    em.clear();
                }

                log.info("PatientManager-modifyPatient-患者信息修改成功");
                return getResultsDTO("患者信息修改成功", true, true);
            }
            else
            {
                log.info("PatientManager-modifyPatient-查询患者为空,无法修改");
                return getResultsDTO("查询患者为空,无法修改", true, true);
            }
        }
        else
        {
            log.info("PatientManager-modifyPatient-患者id为空,无法修改");
            return getResultsDTO("患者id为空，修改失败", true, true);
        }

    }


    private Role getNatureRoleByPatient(Patient pat) throws Hl7Exception
    {
        for (RimCoreRoles r : pat.getPlayerEntity().getPlayerRimCoreRolesList())
        {
            if (r.getCode().code().equals(RoleCode.NATURE.code()))
            {
                return (Role) r;
            }
        }
        return null;
    }


    private void updateNatureRole(Role role, EntitysDTO dto) throws Hl7Exception
    {
        Organization org = (Organization) role.getScoperEntity();
        dto.getOrganization().setOrgId(org.getEntityId().toString());
        organizationManager.updateOrganization(dto.getOrganization());
    }


    // 保存或更新医保信息
    private void saveOrmodifyPatInsurance(Patient patient, List<InfoInsuranceDTO> listInsurance) throws Hl7Exception
    {

        for (InfoInsuranceDTO infoInsurance : listInsurance)
        {

            II yiBaoID = null;
            for (RoleIICode code : RoleIICode.values())
            {
                if (code.getConceptCode() != null && infoInsurance.getId() != null
                        && code.getConceptCode().equals(infoInsurance.getTypeDic().getConceptCode()))
                {
                    yiBaoID = DataTypeUtil.getII(infoInsurance.getId(), infoInsurance.getUnit(), infoInsurance.getState(), DictionaryFactory
                        .getInstance().getCeByDictionaryDTO(infoInsurance.getTypeDic()), code.toString());
                    patient.setId(yiBaoID);
                }
            }
        }
    }


    @Override
    public ResultsDTO findPatient(PatientEncounterDTO patientEncounterDTO, PageDTO pageDTO) throws Hl7Exception
    {
        List<EntitysDTO> patientDtoList = new ArrayList<EntitysDTO>();
        List<Patient> list = findRoleByCond(patientEncounterDTO, pageDTO);
        for (Patient p : list)
        {

            patientDtoList.add(convertByPatient(new EntitysDTO(), p));

        }

        pageDTO.setTotalRecord(findRoleByCount(patientEncounterDTO));
        log.info("查询患者信息成功");
        return getResultsDTO("查询患者信息成功", true, patientDtoList, pageDTO);

    }


    @Override
    public ResultsDTO delPatient(String natureId) throws NumberFormatException, Hl7Exception
    {
        Patient patient = patientQuery.findPatientByNeturalId(natureId);

        if (patient != null)
        {
            II id = patient.getId(RoleIICode.PATIENTID);
            if (id != null)
            {
                List<PatientEncounter> ens = patientEncounterQuery.findAllActivePEByPatientId(natureId);
                if (ens.isEmpty())
                {
                    em.remove(patient);
                }
                else
                {
                    log.info("PatientManager-delPatient-患者还在院中，不能删除");
                    return getResultsDTO("患者还在住院，不能删除", true, false);
                }
            }

        }
        em.flush();
        em.clear();
        return getResultsDTO("删除成功！", true, true);
    }


    @Override
    public ResultsDTO delPatient(List<String> patientList) throws Hl7Exception
    {

        for (String patientId : patientList)
        {

            Patient patient = (Patient) patientQuery.findRoleById(Long.parseLong(patientId));
            if (patient != null)
            {
                II id = patient.getId(RoleIICode.PATIENTID);
                if (id != null)
                {
                    List<PatientEncounter> ens = patientEncounterQuery.findAllActivePE(id.clinicNo().stringValue());
                    if (ens.isEmpty())
                    {
                        em.remove(patient);
                    }
                    else
                    {
                        log.info("PatientManager-delPatient-患者还在院中，不能删除");
                        continue;
                    }
                }

            }
        }
        em.flush();
        em.clear();
        return getResultsDTO("患者还在住院，不能删除", true, true);
    }


    // 患者条件查询
    @Override
    public List<Patient> findRoleByCond(PatientEncounterDTO dto, PageDTO pageDTO) throws Hl7Exception
    {

        List<Patient> patients = patientQuery.findPatientByConditions(dto.getPatientBaseInfoDTO().getNatureId(), dto.getPatientBaseInfoDTO()
            .getNatureName(), dto.getCardId(), dto.getPatientBaseInfoDTO().getSocietyHomeAddress(), pageDTO.getPageSize(), pageDTO.getPageNo());

        return patients;
    }


    // 查询总条数
    public int findRoleByCount(PatientEncounterDTO dto) throws Hl7Exception
    {
        int total = (int) patientQuery.findCountPatientByConditions(dto.getPatientBaseInfoDTO().getNatureId(), dto.getPatientBaseInfoDTO()
            .getNatureName(), dto.getCardId(), dto.getPatientBaseInfoDTO().getSocietyHomeAddress());
        log.info("Patientmanager-findRoleByCount-共" + total + "个患者");
        return total;
    }


    @Override
    public ResultsDTO findPatientByName(String name) throws Hl7Exception
    {
        if (StrUtil.isEmpty(name))
        {
            log.info("名称为空，不能进行查询");
            return this.getResultsDTO("名称为空，不能进行查询", true, null);
        }

        List<Patient> list = patientQuery.findPatientByConditions(null, name, null, null, 0, 0);
        List<EntitysDTO> patientDtoList = new ArrayList<EntitysDTO>();
        for (Patient p : list)
        {
            patientDtoList.add(convertByPatient(new EntitysDTO(), p));
        }

        return this.getResultsDTO("查询成功", true, patientDtoList);
    }


    /**
     * 根据患者角色查询医保信息
     * 
     * @Title: getInfoInsuranceDTOFromPatient
     * @param patient
     *            患者对象
     * @return List<InfoInsuranceDTO>
     * @throws Hl7Exception
     * @firstAuthor Obama
     * @firstTime 2011-03-17 20:08
     * @lastAuthor Obama
     * @lastTime 2011-03-17 20:08
     */
    @Override
    public List<InfoInsuranceDTO> getInfoInsuranceDTOFromPatient(Patient patient)
    {
        List<InfoInsuranceDTO> dtos = new ArrayList<InfoInsuranceDTO>();
        // if (patient == null) {
        // System.out.println("patient空的!!1");
        // }
        for (RimCoreRoleIi roleii : patient.getRoleIiList())
        {
            InfoInsuranceDTO dto = new InfoInsuranceDTO();
            DictionaryDTO dicDto = new DictionaryDTO();
            dto.setId(roleii.getExtensionTxt());
            dto.setUnit(roleii.getIDSouce());
            if (roleii.getRimCoreRoleCdSets() != null)
            {
                dicDto.setCodingschemeChName(roleii.getRimCoreRoleCdSets().getCodingschemeChName());
                dicDto.setCodingschemeEnName(roleii.getRimCoreRoleCdSets().getCodingschemeEnName());
                dicDto.setCodingschemeOid(roleii.getRimCoreRoleCdSets().getCodingschemeOid());
                dicDto.setConceptName(roleii.getRimCoreRoleCdSets().getConceptName());
                dicDto.setConceptCode(roleii.getRimCoreRoleCdSets().getConceptCode());
                dicDto.setVersionName(roleii.getRimCoreRoleCdSets().getRoleVersionNum() == null ? "" : roleii.getRimCoreRoleCdSets().getRoleVersionNum()
                    .toString());
                dto.setTypeDic(dicDto);
                dtos.add(dto);
            }
        }
        return dtos;
    }


    @Override
    public boolean isOutHospital(String patientNatureId) throws Hl7Exception
    {

        List<PatientEncounter> encounters = patientEncounterQuery.findAllActivePEByPatientId(patientNatureId);

        if (encounters.isEmpty())
        {
            return true;
        }
        else if (encounters.size() > 1)
        {
            return false;
        }
        else if (encounters.get(0).getCode().code().equals(ActCode.DISCHARGED.code()))
        {
            return true;
        }
        else
        {
            return false;
        }

    }


    @Override
    public PatientEncounterDTO findPatientByBedNoAndWorkgroupId(String bedNo, String workgroupId) throws Hl7Exception
    {

        List<PatientEncounter> acts = patientEncounterQuery.findPatientByBedNoAndWorkgroupId(bedNo, workgroupId);

        PatientEncounterDTO dto = new PatientEncounterDTO();
        if (acts.isEmpty())
        {
            return dto;
        }
        else
        {

            PatientEncounter inde = acts.get(0);
            ReceivingManagerLocal manager = (ReceivingManagerLocal) Component.getInstance("ReceivingManager");
            dto = manager.converByIndepartment(inde);
            return dto;
        }

    }


    @Override
    public ResultsDTO findPatientResultsByBedNoAndWorkgroupId(String bedNo, String workgroupId) throws Hl7Exception
    {
        PatientEncounterDTO dto = findPatientByBedNoAndWorkgroupId(bedNo, workgroupId);
        return getResultsDTO("返回", true, dto);
    }


    @Override
    public void updatePatientBaseInfo(EntitysDTO dto) throws Hl7Exception
    {
        if (!StrUtil.isEmpty(dto.getPatientBaseInfo().getNatureId()))
        {

            PatientQueryDTO patientQueryDTO = new PatientQueryDTO();
            patientQueryDTO.setPatientId(dto.getPatientBaseInfo().getNatureId());

            Person person = (Person) patientQuery.findHl7EntityById(Long.parseLong(dto.getPatientBaseInfo().getNatureId()));
            if (person == null)
            {
                log.info("PatientManager-updatePatientBaseInfo-患者为空！更新失败");
                return;
            }
            // 修改人的信息
            personManager.modifyPerson(person, dto);
            update(person);
            log.info("患者信息修改成功");

        }
        else
        {
            newPatientIndex(dto);
        }
    }


    private EntitysDTO convertByPatient(EntitysDTO entityDTO, Patient patient) throws Hl7Exception
    {
        Person p = (Person) patient.getPlayerEntity();
        personManager.converPersonInfo(entityDTO, p);

        Role natureRole = null;

        entityDTO.getPatientBaseInfo().setNatureId(
            patient.getId(RoleIICode.PATIENTID) != null ? patient.getId(RoleIICode.PATIENTID).extension().stringValue() : null);
        for (RoleIICode code : RoleIICode.values())
        {
            if (code.getClazz().equals(Patient.class) && code.getConceptCode() != null)
            {

                II ii = patient.getId(code);
                if (ii == null)
                {
                    continue;
                }
                entityDTO.getListInsurance().add(convertInfoInsuranceDTO(ii));
            }
        }

        return entityDTO;
    }


    // 组装证件
    private MedicalCardDTO convertMedicalCardDTO(II ii) throws Hl7Exception
    {
        MedicalCardDTO medicalCard = new MedicalCardDTO();
        medicalCard.setId(ii.extension().stringValue());
        medicalCard.setState(ii.iiState() != null ? ii.iiState().stringValue() : null);
        medicalCard.setTypeDic(getDictionaryFactory().getDictionaryDTOByCe(ii.iiType()));
        medicalCard.setOffice(ii.iiSouce() != null ? ii.iiSouce().stringValue() : null);
        return medicalCard;
    }


    // 组装医保号
    private InfoInsuranceDTO convertInfoInsuranceDTO(II ii) throws Hl7Exception
    {
        InfoInsuranceDTO medicalCard = new InfoInsuranceDTO();
        if (ii != null)
        {
            medicalCard.setId(ii.extension().stringValue());
            medicalCard.setState(ii.iiState() != null ? ii.iiState().stringValue() : null);
            medicalCard.setTypeDic(getDictionaryFactory().getDictionaryDTOByCe(ii.iiType()));
            medicalCard.setUnit(ii.iiSouce() != null ? ii.iiSouce().stringValue() : null);
        }
        return medicalCard;
    }


    @Override
    public Patient findOrCreatePateint(PatientEncounterDTO dto) throws Hl7Exception
    {

        Patient patient = null;
        if (StrUtil.isNotEmpty(dto.getPatientBaseInfoDTO().getNatureId()))
        {
            log.info("PatientManager-getOrCreatePateint-查询患者信息");
            patient = patientQuery.findPatientByNeturalId(dto.getPatientBaseInfoDTO().getNatureId());

        }
        else
        {
            // 保存患者信息到患者主索引
            EntitysDTO enDTO = new EntitysDTO();
            enDTO.setPatientBaseInfo(dto.getPatientBaseInfoDTO());
            log.info("PatientManager-getOrCreatePateint-保存患者信息到患者主索引");
            InfoInsuranceDTO inDTO = new InfoInsuranceDTO();
            inDTO.setId(dto.getInsuranceId());
            inDTO.setTypeDic(dto.getInsuranceTypeDic());
            enDTO.getListInsurance().add(inDTO);

            MedicalCardDTO cardDTO = new MedicalCardDTO();
            cardDTO.setId(dto.getCardId());
            cardDTO.setTypeDic(dto.getCardTypeDic());

            enDTO.getListMedicalCard().add(cardDTO);

            patient = patientManager.newPatientNotPersist(enDTO);

        }
        return patient;
    }


    // 验证主索引
    private ResultsDTO validateNewIndex(EntitysDTO entitysDTO) throws Hl7Exception
    {
        if (StrUtil.isNotEmpty(entitysDTO.getPatientBaseInfo().getNatureId()))
        {
            Patient p = patientQuery.findPatientByNeturalId(entitysDTO.getPatientBaseInfo().getNatureId());
            if (p != null)
            {
                log.info("PatientManager-validateNewIndex-患者已存在!");
                return getResultsDTO("新建失败！", true, false);
            }
        }
        for (MedicalCardDTO dto : entitysDTO.getListMedicalCard())
        {
            if (patientQuery.validateEntityIIExsit(dto.getId(), dto.getTypeDic().getCodingschemeEnName(), dto.getTypeDic().getConceptCode()))
            {
                return getResultsDTO("身份证号重复,请重新输入", true, false);
            }
        }
        for (InfoInsuranceDTO dto : entitysDTO.getListInsurance())
        {
            if (patientQuery.validateRoleIIExsit(dto.getId(), dto.getTypeDic().getCodingschemeEnName(), dto.getTypeDic().getConceptCode()))
            {
                return getResultsDTO("医保号重复,请重新输入", true, false);
            }
        }

        return null;
    }


    @Override
    public ResultsDTO findAdmitDetail(String natureId) throws Hl7Exception
    {
        if (StrUtil.isEmpty(natureId))
        {
            return this.getResultsDTO("", true, null);
        }

        Patient p = patientQuery.findPatientByNeturalId(natureId);
        List<String> list = new ArrayList<String>();

        String inhosNum = null;
        for (ActParticipation part : p.getParticipations())
        {
            if (part.getTypecode().equals(ParticipationType.SBJ) && part.getParticipationAct().getCode().code().equals(ActCode.HOSPITALIZED.code()))
            {
                if (part.getSequenceNumber() != null && part.getSequenceNumber().intValue() != 0)
                {

                    inhosNum = part.getSequenceNumber().intValue() + "";
                }
            }
        }
        if (inhosNum == null)
        {
            inhosNum = "0";
        }
        list.add(inhosNum);
        II inhosNo = p.getId(RoleIICode.ADMISSIONNO);
        if (inhosNo != null && inhosNo.extension() != null)
        {
            list.add(inhosNo.extension().stringValue());
        }
        else
        {
            list.add(null);
        }

        log.info("");
        return this.getResultsDTO("", true, list);
    }


    // 获取person
    private Person constructPerson(EntitysDTO entitysDTO) throws Hl7Exception
    {
        // 创建一个Person
        Person person = null;
        if (StrUtil.isNotEmpty(entitysDTO.getPatientBaseInfo().getPersonId()))
        {
            person = (Person) patientQuery.findHl7EntityById(Long.parseLong(entitysDTO.getPatientBaseInfo().getPersonId()));

        }
        @SuppressWarnings("unused")
        boolean thesame = false;
        if (person == null)
        {
            person = personManager.findSamePerson(entitysDTO.getPatientBaseInfo().getNatureName(), entitysDTO.getPatientBaseInfo().getNatureSexDic()
                .getConceptCode(), entitysDTO.getPatientBaseInfo().getNatureBirthdate());
            if (person != null)
            {
                log.info("PatientManager-newPatientIndex-人的实体已存在，修改其基本信息");
                personManager.modifyPerson(person, entitysDTO);
                thesame = true;
            }
            else
            {
                log.info("PatientManager-newPatientIndex-不存在此人，新建其基本信息");
                person = personManager.newPerson(entitysDTO);
            }
        }
        return person;
    }


    private Organization constructOrg(EntitysDTO entityDTO) throws Hl7Exception
    {
        // 创建一个社会(单位)组织
        Organization organization = null;
        if (!StrUtil.isEmpty(entityDTO.getOrganization().getOrgName()))
        {

            organization = organizationQuery.findOrganizationByOrgName(entityDTO.getOrganization().getOrgName());

        }
        if (organization == null)
        {
            organization = organizationManager.newOrganizationNotPersist(entityDTO.getOrganization());
            log.info("构建社会组织");
        }
        return organization;
    }


    // 构建自然(社会)角色
    private Role constructNatureRole(EntitysDTO entityDTO, Person person) throws Hl7Exception
    {
        Organization workplace = constructOrg(entityDTO);

        // 给person赋自然角色
        Role natureRole = this.getRoleFactory().newIdentifiedEntity(getDataTypeFactory().newCE(RoleCode.NATURE.code().toString()), person, workplace,
            null);

        return natureRole;
    }


    // 创建患者
    private Patient constructPatient(EntitysDTO entityDTO, Person person) throws Hl7Exception
    {

        OrganizationDTO orgDTO = new OrganizationDTO();

        orgDTO.setOrgName("大庆油田总医院");
        Organization organization = organizationQuery.findOrganizationByOrgName(orgDTO.getOrgName());
        if (organization == null)
        {
            organization = organizationManager.newOrganizationNotPersist(orgDTO);
            log.info("新建医院");
        }
        else
        {
            log.info("找到医院");
        }

        // 患者ID
        String parientId = null;
        if (StrUtil.isNotEmpty(entityDTO.getPatientBaseInfo().getNatureId()))
        {
            parientId = entityDTO.getPatientBaseInfo().getNatureId();
        }
        else
        {
            parientId = getSEQ_CLINICNO();
        }

        II patientID = DataTypeUtil.getII(root, parientId, "true", RoleIICode.PATIENTID.toString());
        Patient patient = this.getRoleFactory().newPatient(getDataTypeFactory().newCE(RoleCode.PATIENT.code().toString()), person, organization, null);
        // 保存患者ID
        patient.setId(patientID);
        saveOrmodifyPatInsurance(patient, entityDTO.getListInsurance());

        return patient;
    }


    // 构造家庭组织实体
    private Organization construtOrganization(EntitysDTO entityDTO) throws Hl7Exception
    {
        // 创建一个家庭组织
        OrganizationDTO orgDTO = new OrganizationDTO();
        orgDTO.setOrgName(entityDTO.getPatientBaseInfo().getNatureName() + "的家庭组织");
        Organization familyOrgan = organizationQuery.findOrganizationByOrgName(orgDTO.getOrgName());
        if (familyOrgan == null)
        {
            familyOrgan = organizationManager.newOrganizationNotPersist(orgDTO);
        }
        return familyOrgan;
    }


    private void modifyFamilyRole()
    {

    }


    // 构造家庭组织角色
    private List<Role> constructFamilyRole(EntitysDTO entityDTO, Person person) throws Hl7Exception
    {
        List<Role> familyRoles = new ArrayList<Role>();
        // 家庭信息集合
        Organization familyOrgan = construtOrganization(entityDTO);
        for (InfoHomeDTO infoHomeDTO : entityDTO.getListHome())
        {
            // 得到一个家庭关系person
            EntitysDTO homeDTO = new EntitysDTO();
            homeDTO.getPatientBaseInfo().setNatureName(infoHomeDTO.getName());
            Person homePerson = personManager.newPerson(homeDTO);

            // 创建家庭角色
            Role familyRole = this.getRoleFactory().newIdentifiedEntity(getDataTypeFactory().newCE(RoleCode.FAMILY.code().toString()), homePerson,
                familyOrgan, null);
            familyRoles.add(familyRole);
        }
        return familyRoles;
    }


    @Override
    public Patient newPatientNotPersist(EntitysDTO dto) throws Hl7Exception
    {
        Person person = constructPerson(dto);
        Patient patient = constructPatient(dto, person);
        return patient;
    }

}
